package com.ruoyi.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.web.domain.MesBindingAllocation;
import com.ruoyi.web.domain.mes.MesMachineRelevance;
import com.ruoyi.web.domain.mes.MesPrintTechnologyDetail;
import com.ruoyi.web.domain.vo.AllocationMachineVo;
import com.ruoyi.web.mapper.ProduceMapper;
import com.ruoyi.web.mapper.SupplierCheckoutMapper;
import com.ruoyi.web.vo.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProduceService extends ServiceImpl<ProduceMapper, Produce> {


    @Resource
    private ProduceService produceService;
    @Resource
    private ProducePrintService producePrintService;
    @Resource
    private ProduceProductService produceProductService;
    @Resource
    private MesPrintTechnologyDetailService mesPrintTechnologyDetailService;
    @Resource
    private MesBindingAllocationService mesBindingAllocationService;
    @Resource
    private MesMachineService mesMachineService;
    @Resource
    private ProduceMapper produceMapper;
    @Resource
    private MesMachineRelevanceService mesMachineRelevanceService;
    @Resource
    private MesRotateService mesRotateService;
    @Resource
    private SysDictDataMapper dictDataMapper;
    @Resource
    private ProducePieceService producePieceService;
    @Resource
    private MesProducePieceMachineService mesProducePieceMachineService;


//    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Transactional
    public int AllocationMachine(String pid) {
        List<ProducePrint> producePrintList = producePrintService.list(new QueryWrapper<ProducePrint>()
                .lambda().eq(ProducePrint::getProduceId, pid).orderByDesc(ProducePrint::getPrintAmount));//查询印刷单
        if (producePrintList != null && producePrintList.size() != 0) {
           int fp= fpmachine(pid,producePrintList);//分配机台
            if(fp==1){
                //更改生产单分配
                produceService.update(new UpdateWrapper<Produce>().lambda()
                        .set(Produce::getIsFp, "1").eq(Produce::getProduceId, pid));
            }
        }else{
//            throw new ServiceException("生产单没有对应的印刷信息");
            errorinfo("生产单没有对应的印刷信息");
        }
        return 1;
    }

    //目录分配机台
//    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Transactional
    public int MlMachine(String pid) {
        List<ProducePrint> producePrintList = producePrintService.list(new QueryWrapper<ProducePrint>()
                .lambda().eq(ProducePrint::getProduceId, pid)
                .eq(ProducePrint::getBreed,"目录")
                .orderByDesc(ProducePrint::getPrintAmount));//查询印刷单
        if(producePrintList!=null&&producePrintList.size()>0){
            fpmachine(pid,producePrintList);//分配机台
            return 1;
        }else{
            return 1;
        }
    }


    public int fpmachine(String pid, List<ProducePrint> producePrintList){
        List<Produce> produce = produceService.list(new QueryWrapper<Produce>()
                .lambda().eq(Produce::getProduceId, pid));//查询生产单
        //存同一个产品同一印刷方式分配的机台
        List<AllocationMachineVo> allocationMachineVos = new ArrayList<>();
        //印刷单
        for (ProducePrint producePrint : producePrintList) {
            //生产印刷单对应产品信息
            List<ProduceProduct> products = produceProductService.list(new QueryWrapper<ProduceProduct>()
                    .lambda().eq(ProduceProduct::getProduceId, pid)
                    .eq(ProduceProduct::getOrderProductId, producePrint.getOrderProductId()));
            if (products == null || products.isEmpty()) {
//                throw new ServiceException("印刷单没有找到对应的产品信息！");
                errorinfo("印刷单没有找到对应的产品信息！");
            }
            ProduceProduct product = products.get(0);

            Map<String, String> params = new HashMap<>();//存储最各类型任务量最少的机台
            List<MesProducePieceMachine> mesProducePieceMachineList = new ArrayList<>();
            List<MesPrintTechnologyDetail> gylist = mesPrintTechnologyDetailService.list(new QueryWrapper<MesPrintTechnologyDetail>()
                    .lambda().eq(MesPrintTechnologyDetail::getTechnologyId, producePrint.getTechnologyId()
                    ).orderByAsc(MesPrintTechnologyDetail::getProcedureOrder));//工艺

            for (MesPrintTechnologyDetail mesPrintTechnologyDetail : gylist) {//工艺
                MesMachine mesMachine = new MesMachine();
                mesMachine.setType(mesPrintTechnologyDetail.getMachineType());//机器类型
                if(!Objects.equals(producePrint.getBreed(), "目录")){
                    if(Objects.equals(product.getColor(), "1")) {//目录并且是单黑过滤内文分配状态
                        mesMachine.setProduceType(produce.get(0).getType());
                    }
                }
                if (Objects.equals(mesPrintTechnologyDetail.getMachineType(), "2")) {//如果是印刷机
                    mesMachine.setWorkshopId(produce.get(0).getWorkshopId());//车间id
                    if (Objects.equals(producePrint.getPrintType(), "1")) {//印刷方式，1平张 2卷轮
                        mesMachine.setModel("1");
                    }
                    if (Objects.equals(producePrint.getPrintType(), "2")) {//印刷方式，1平张 2卷轮
                        mesMachine.setModel("2");
                    }
                }
                if (Objects.equals(mesPrintTechnologyDetail.getMachineType(), "3") && Objects.equals(produce.get(0).getType(), "2")) {//如果是内文并且是装订机
//                        if (Objects.equals(product.getBindingMode(), "7") || Objects.equals(product.getBindingMode(), "9")) {
////                                return;//目录无需分配机台
//                        } else {
//                            if (Objects.equals(product.getBookSize(), "1")) {//如果开本数等于8
//                                List<MesBindingAllocation> allocations = mesBindingAllocationService.list(new QueryWrapper<MesBindingAllocation>()
//                                        .lambda().eq(MesBindingAllocation::getBookSize, product.getBookSize()));
//                                params.put(mesPrintTechnologyDetail.getMachineType(), allocations.get(0).getMachineId());
////                                continue;//跳出本次循环
//                            } else {
//                                String machineId = params.get("2");//分配的印刷机台
//                                MesMachine workshop = mesMachineService.getById(machineId);//分配的印刷车间
//
//                                List<MesBindingAllocation> bindingAllocations = mesBindingAllocationService.list(new QueryWrapper<MesBindingAllocation>()
//                                        .lambda().eq(MesBindingAllocation::getPrintWorkshopId, workshop.getWorkshopId())
//                                        .like(MesBindingAllocation::getBindingMode, product.getBindingMode()));
//                                if (bindingAllocations == null || bindingAllocations.size() == 0) {
//                                    throw new ServiceException(workshop.getWorkshopName() + product.getBindingMode() + "装订方式" + "没有查到装订对应机台数据！");
//                                } else {
//                                    if (bindingAllocations.size() > 1) {//胶订
//                                        MesBindingAllocation bindingAllocation = mesBindingAllocationService.list(new QueryWrapper<MesBindingAllocation>()
//                                                .lambda().eq(MesBindingAllocation::getPrintWorkshopId, workshop.getWorkshopId())
//                                                .like(MesBindingAllocation::getBindingMode, product.getBindingMode())
//                                                .lt(MesBindingAllocation::getPrintSheet, product.getSheet())
//                                                .orderByDesc(MesBindingAllocation::getPrintSheet)).get(0);
//                                        String Machines = bindingAllocation.getMachineId();//逗号隔开的机台组
//                                        List<MesMachine> machines = produceMapper.getbindingLeast(Machines);//查询机台
//                                        if (machines != null && machines.size() > 0) {
//                                            params.put(mesPrintTechnologyDetail.getMachineType(), machines.get(0).getPid());
//                                        } else {
//                                            throw new ServiceException("胶钉没有查到对应机台信息！");
//                                        }
////                                        params.put(mesPrintTechnologyDetail.getMachineType(), bindingAllocation.getMachineId());
////                                        continue;//跳出本次循环
//                                    } else {//骑马订
//                                        String Machines = bindingAllocations.get(0).getMachineId();//逗号隔开的机台组
//                                        if (Objects.equals(producePrint.getPrintType(), "1")) {//印刷方式，1平张 2卷轮
//                                            List<MesMachine> machines = produceMapper.getbindingLeast(Machines);//查询机台
//                                            if (machines != null && machines.size() > 0) {
//                                                params.put(mesPrintTechnologyDetail.getMachineType(), machines.get(0).getPid());
////                                            continue;//跳出本次循环
//                                            } else {
//                                                throw new ServiceException("骑马钉没有查到对应机台信息！");
//                                            }
//                                        }else{
//                                            params.put(mesPrintTechnologyDetail.getMachineType(), Machines.split(",")[0]);
//                                        }
//                                    }
//                                }
//                            }
//                        }
                }
                if (Objects.equals(mesPrintTechnologyDetail.getMachineType(), "4")) {//折页根据印刷车间过滤
                    mesMachine.setWorkshopId(produce.get(0).getWorkshopId());
                }
                List<MesMachine> machines = getMachines(mesMachine);//查询任务量最少机台
                if (machines == null || machines.size() == 0) {
//                    throw new ServiceException("机台类型" + mesPrintTechnologyDetail.getMachineType() + "没有查到对应机台数据！");
                    errorinfo("机台类型" + mesPrintTechnologyDetail.getMachineType() + "没有查到对应机台数据！");
                }
                if (Objects.equals(mesPrintTechnologyDetail.getMachineType(), "4")) {//如果是折页
                    //印张是0.25的目录分到固定的机台
                    if (Objects.equals(producePrint.getBreed(), "目录") && Objects.equals(producePrint.getSheet(), "0.25")) {
                        params.put(mesPrintTechnologyDetail.getMachineType(), "239a8b35-f4c4-11ee-95b2-eb7791728751");
                    } else {
                        if (new Double(producePrint.getSheet()) < 1) {//如果是半代,半代对应半代折页机，整代选择印刷对应的折页机
                            List<MesMachine> machine = machines.stream().filter(it -> it.getEra().equals("1"))
                                    .sorted(Comparator.comparing(MesMachine::getTotal)).collect(Collectors.toList());
                            if (machine == null || machine.size() == 0) {
//                                throw new ServiceException("没有半代折页机，无法分配！");
                                errorinfo("没有找到半代折页机，无法分配！");
                            } else {
                                //任务量最少的半代折页机台
                                params.put(mesPrintTechnologyDetail.getMachineType(), machine.get(0).getPid());
                            }
                        } else {//如果是整代
                            List<MesMachine> machine = machines.stream().filter(it -> it.getEra().equals("2"))
                                    .sorted(Comparator.comparing(MesMachine::getTotal)).collect(Collectors.toList());
                            if (machine == null || machine.size() == 0) {
//                                throw new ServiceException("没有整代折页机，无法分配！");
                                errorinfo("没有找到整代折页机，无法分配！");
                            } else {
                                String printmachineId = params.get("2");//印刷机台
                                //查询印刷对应折页机台
                                List<MesMachineRelevance> foldmachine = mesMachineRelevanceService.list(new QueryWrapper<MesMachineRelevance>()
                                        .lambda().eq(MesMachineRelevance::getPrintMachineId, printmachineId));
                                if (foldmachine != null && foldmachine.size() > 0) {
                                    //印刷机对应的折页机
                                    params.put(mesPrintTechnologyDetail.getMachineType(), foldmachine.get(0).getFoldMachineId());
                                } else {
                                    //任务量最少的折页机
                                    if (Objects.equals(produce.get(0).getWorkshopId(), "10")) {//四车间默认公共折页机
                                        params.put(mesPrintTechnologyDetail.getMachineType(), "cc368fbf26a54b73830863aaad93e76e");
                                    } else if (Objects.equals(produce.get(0).getWorkshopId(), "7")) {//一车间默认公共折页机
                                        params.put(mesPrintTechnologyDetail.getMachineType(), "68a1cb756cc24d05abf495c3915fab74");
                                    } else {
                                        params.put(mesPrintTechnologyDetail.getMachineType(), machine.get(0).getPid());
                                    }
                                }
                            }
                        }
                    }
                } else if (Objects.equals(mesPrintTechnologyDetail.getMachineType(), "2")) {//如果是印刷
                    List<AllocationMachineVo> MachineVos = allocationMachineVos.stream()
                            .filter(t -> t.getOrderProductId().equals(producePrint.getOrderProductId()))//产品id
                            .filter(t -> t.getType().equals("2"))//机台类型
                            .filter(t -> t.getPrintType().equals(producePrint.getPrintType()))//印刷方式
                            .collect(Collectors.toList());
                    //判断同一产品同一印刷方式是否已分配机台
                    if (MachineVos != null && MachineVos.size() > 0) {
                        params.put(mesPrintTechnologyDetail.getMachineType(), MachineVos.get(0).getMachineId());
                    } else {
                        //如果是内文
                        if (Objects.equals(produce.get(0).getType(), "2")) {
                            //根据条件查询平板双色轮流机台(板材尺寸，品种，印色)
                            List<MesRotate> mesRotates = mesRotateService.list(new QueryWrapper<MesRotate>()
                                    .lambda().eq(MesRotate::getType, produce.get(0).getType())
                                    .eq(MesRotate::getSheetSize, product.getSheetSize())//板材尺寸
                                    .like(MesRotate::getPrintColor, product.getPrintColor())//印色
                            );
                            if (mesRotates != null && !mesRotates.isEmpty()) {
                                if(Objects.equals(product.getBreedType(), "目录")){//内文目录
                                    List<MesRotate> Rotate = mesRotates.stream().filter(it -> it.getBreed()
                                            .equals("目录")).collect(Collectors.toList());
                                    if(Rotate!=null&&Rotate.size()>0){
                                        mesMachine.setPid(Rotate.get(0).getMachineId());
                                        List<MesMachine> mesMachines= getMachines(mesMachine);
                                        params.put(mesPrintTechnologyDetail.getMachineType(), mesMachines.get(0).getPid());
                                    }else{
                                        List<MesMachine> machine = machines.stream().filter(it -> it.getSize().equals(producePrint.getSheetSize()))
                                                .sorted(Comparator.comparing(MesMachine::getTotal)).collect(Collectors.toList());
                                        if (machine == null || machine.size() == 0) {
                                            String sheetSizeLabel = dictDataMapper.selectDictLabel("ems_machine_info_size", producePrint.getSheetSize());
//                                            throw new ServiceException(sheetSizeLabel + "板材尺寸没有所对应的印刷机，无法分配！");
                                            errorinfo(sheetSizeLabel + "板材尺寸没有所对应的印刷机，无法分配！");
                                        } else {
                                            params.put(mesPrintTechnologyDetail.getMachineType(), machine.get(0).getPid());
                                        }
                                    }
                                }else{//内文蓝黑
                                    List<MesRotate> Rotate = mesRotates.stream().filter(it -> it.getColor()
                                            .equals(product.getColor())).collect(Collectors.toList());
                                    if(Rotate!=null&&Rotate.size()>0){
                                        mesMachine.setPid(Rotate.get(0).getMachineId());
                                        List<MesMachine> mesMachines= getMachines(mesMachine);
                                        params.put(mesPrintTechnologyDetail.getMachineType(), mesMachines.get(0).getPid());
                                    }else{
                                        List<MesMachine> machine = machines.stream().filter(it -> it.getSize().equals(producePrint.getSheetSize()))
                                                .sorted(Comparator.comparing(MesMachine::getTotal)).collect(Collectors.toList());
                                        if (machine == null || machine.size() == 0) {
                                            String sheetSizeLabel = dictDataMapper.selectDictLabel("ems_machine_info_size", producePrint.getSheetSize());
//                                            throw new ServiceException(sheetSizeLabel + "板材尺寸没有所对应的印刷机，无法分配！");
                                            errorinfo(sheetSizeLabel + "板材尺寸没有所对应的印刷机，无法分配！");
                                        } else {
                                            params.put(mesPrintTechnologyDetail.getMachineType(), machine.get(0).getPid());
                                        }
                                    }
                                }
                            } else {
                                List<MesMachine> machine = machines.stream().filter(it -> it.getSize().equals(producePrint.getSheetSize()))
                                        .sorted(Comparator.comparing(MesMachine::getTotal)).collect(Collectors.toList());
                                if (machine == null || machine.size() == 0) {
                                    String sheetSizeLabel = dictDataMapper.selectDictLabel("ems_machine_info_size", producePrint.getSheetSize());
//                                    throw new ServiceException(sheetSizeLabel + "板材尺寸没有所对应的印刷机，无法分配！");
                                    errorinfo(sheetSizeLabel + "板材尺寸没有所对应的印刷机，无法分配！");
                                } else {
                                    params.put(mesPrintTechnologyDetail.getMachineType(), machine.get(0).getPid());
                                }
                            }
                        }
                        else {
                            //封面 板材尺寸和印色
                            List<MesRotate> mesRotates = mesRotateService.list(new QueryWrapper<MesRotate>()
                                    .lambda().eq(MesRotate::getType, produce.get(0).getType())
                                    .eq(MesRotate::getSheetSize, producePrint.getSheetSize())
                                    .like(MesRotate::getPrintColor, producePrint.getPrintColour()));

                            if (mesRotates != null && !mesRotates.isEmpty()) {
                                if(Objects.equals(product.getColor(), "2")){//蓝黑
                                    List<MesRotate> Rotate = mesRotates.stream().filter(it -> it.getColor()
                                            .equals("2")).collect(Collectors.toList());
                                    if(Rotate!=null&&Rotate.size()>0){
                                        mesMachine.setPid(Rotate.get(0).getMachineId());
                                        List<MesMachine> mesMachines= getMachines(mesMachine);
                                        params.put(mesPrintTechnologyDetail.getMachineType(), mesMachines.get(0).getPid());
                                    }else{
//                                        throw new ServiceException("封面蓝黑没有找到对应的印刷机，无法分配！");
                                        errorinfo("封面蓝黑没有找到对应的印刷机，无法分配！");
                                    }
                                }else{//不是蓝黑
                                    List<MesRotate> Rotate = mesRotates.stream().filter(it -> !it.getColor()
                                            .equals("2")).collect(Collectors.toList());
                                    if(Rotate!=null&&Rotate.size()>0){
                                        mesMachine.setPid(Rotate.get(0).getMachineId());
                                        List<MesMachine> mesMachines= getMachines(mesMachine);
                                        params.put(mesPrintTechnologyDetail.getMachineType(), mesMachines.get(0).getPid());
                                    }else{
//                                        throw new ServiceException("封面没有找到蓝黑以外对应的印刷机，无法分配！");
                                        errorinfo("封面没有找到蓝黑以外对应的印刷机，无法分配！");
                                    }
                                }
                            }else{
                                List<MesMachine> machine = machines.stream().filter(it -> it.getSize().equals(producePrint.getSheetSize()))
                                        .sorted(Comparator.comparing(MesMachine::getTotal)).collect(Collectors.toList());
                                if (machine == null || machine.size() == 0) {
                                    String sheetSizeLabel = dictDataMapper.selectDictLabel("ems_machine_info_size", producePrint.getSheetSize());
//                                    throw new ServiceException(sheetSizeLabel + "板材尺寸没有所对应的印刷机，无法分配！");
                                    errorinfo(sheetSizeLabel + "板材尺寸没有所对应的印刷机，无法分配！");
                                } else {
                                    params.put(mesPrintTechnologyDetail.getMachineType(), machine.get(0).getPid());
                                }
                            }
                        }
                    }
                }//白纸裁切
                else if (Objects.equals(mesPrintTechnologyDetail.getMachineType(), "5")) {
                    mesMachine.setPid("93e3ea062fa94418acb64dbe05b3d28d");
                    List<MesMachine> mesMachines= getMachines(mesMachine);
                    params.put(mesPrintTechnologyDetail.getMachineType(), mesMachines.get(0).getPid());
                }//封面裁切
                else if (Objects.equals(mesPrintTechnologyDetail.getMachineType(), "6")) {
                    mesMachine.setPid("f0f23a60bacf4f2e81fa04c4d8ea9b6d");
                    List<MesMachine> mesMachines= getMachines(mesMachine);
                    params.put(mesPrintTechnologyDetail.getMachineType(), mesMachines.get(0).getPid());
                }//覆膜
                else if (Objects.equals(mesPrintTechnologyDetail.getMachineType(), "7")) {
                    MesMachine covermachine=new MesMachine();
                    covermachine.setType("7");
                    covermachine.setProduceType(produce.get(0).getType());
                    List<MesMachine> covers = produceMapper.getcoverLeast(covermachine);//查询覆膜机任务量最少机台
                    params.put(mesPrintTechnologyDetail.getMachineType(), covers.get(0).getPid());
                }
                else {
                    String fmachine = params.get(mesPrintTechnologyDetail.getMachineType());
                    if (StringUtils.isEmpty(fmachine)) {
                        params.put(mesPrintTechnologyDetail.getMachineType(), machines.get(0).getPid());
                    }
                }
            }

            List<ProducePiece> producePieceList = producePieceService.list(new QueryWrapper<ProducePiece>()
                    .lambda().eq(ProducePiece::getPrintId, producePrint.getPrintId()));//生产单贴数

            for (ProducePiece producePiece : producePieceList) {//贴数
                for (MesPrintTechnologyDetail mesPrintTechnologyDetail : gylist) {//工艺
                    MesProducePieceMachine mesProducePieceMachine = new MesProducePieceMachine();

                    //任务量最少的机台
                    String machineId = params.get(mesPrintTechnologyDetail.getMachineType());
                    mesProducePieceMachine.setId(UUID.randomUUID().toString().replace("-", ""));
                    mesProducePieceMachine.setPieceId(producePiece.getPieceId());//贴数id
                    mesProducePieceMachine.setCreateTime(DateUtils.getNowDate());//创建时间
                    mesProducePieceMachine.setExpectTime(produce.get(0).getDeliverDate());//预计交货日期

                    //装订暂不分配
                    if(!Objects.equals(mesPrintTechnologyDetail.getMachineType(), "3")) {
                        mesProducePieceMachine.setMachineId(machineId);//分配机台id
                    }
                    mesProducePieceMachine.setMachineType(mesPrintTechnologyDetail.getMachineType());//类型
                    mesProducePieceMachine.setStep(mesPrintTechnologyDetail.getProcedureOrder());//步骤


                    if(Objects.equals(producePiece.getBreed(), "目录")) {
                        List<MesProducePieceMachine> pieceMachines=mesProducePieceMachineService.list(new QueryWrapper<MesProducePieceMachine>()
                                .lambda().eq(MesProducePieceMachine::getPieceId,producePiece.getPieceId())
                                .eq(MesProducePieceMachine::getMachineType,mesPrintTechnologyDetail.getMachineType()));
                        if(pieceMachines==null||pieceMachines.size()==0){
                            mesProducePieceMachineList.add(mesProducePieceMachine);
                        }
                    }else{
                        mesProducePieceMachineList.add(mesProducePieceMachine);
                    }
                }
            }
            mesProducePieceMachineService.saveBatch(mesProducePieceMachineList);
            for (MesProducePieceMachine pieceMachine : mesProducePieceMachineList) {
                AllocationMachineVo m = new AllocationMachineVo();
                m.setType(pieceMachine.getMachineType());//机台类型
                m.setMachineId(pieceMachine.getMachineId());//分配机台id
                m.setPrintId(producePrint.getPrintId());//印刷单id
                m.setOrderProductId(producePrint.getOrderProductId());//印刷单产品id
                m.setPrintType(producePrint.getPrintType());//印刷方式
                //验证同一产品的同一印刷方式
                List<AllocationMachineVo> allocationMachineVos1 = allocationMachineVos.stream()
                        .filter(t -> t.getOrderProductId().equals(m.getOrderProductId()))
                        .filter(t -> t.getType().equals(m.getType()))
                        .filter(t -> t.getPrintType().equals(m.getPrintType()))
                        .collect(Collectors.toList());
                if (allocationMachineVos1 == null || allocationMachineVos1.size() == 0) {
                    allocationMachineVos.add(m);
                }
            }
        }
        return 1;
    }


    public List<MesMachine> getMachines(MesMachine machine){
        if(machine.getPid()!=null&& !machine.getPid().isEmpty()){
            machine.setWorkshopId(null);
        }
       List<MesMachine> machines= produceMapper.getTypeLeast(machine);
       if(machines!=null&&machines.size()>0){
           return machines;
       }else{
//           throw new ServiceException("没有查询到可分配机台");
           errorinfo("没有查询到可分配机台");
           return null;
       }
    }

    public void errorinfo(String info){
            throw new ServiceException(info);
    }

    public String getWorkshop(String machineId){
        MesMachine workshop1 = mesMachineService.getById(machineId);
        if(Objects.equals(workshop1.getWorkshopId(), "8")){
            return "7";
        }else{
            return "10";
        }
    }

    //装订分配机台
//    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Transactional
    public int BindingMachine(String pid) {
        List<Produce> produce = produceService.list(new QueryWrapper<Produce>()
                .lambda().eq(Produce::getProduceId, pid));//查询生产单
        List<ProducePrint> producePrintList = producePrintService.list(new QueryWrapper<ProducePrint>()
                .lambda().eq(ProducePrint::getProduceId, pid).orderByDesc(ProducePrint::getPrintAmount));//查询印刷单

        String workshopId="0";

        if (producePrintList != null && producePrintList.size() != 0) {
            for (ProducePrint producePrint : producePrintList) {//印刷单
                String seId="0";

                //生产印刷单对应产品信息
                List<ProduceProduct> products = produceProductService.list(new QueryWrapper<ProduceProduct>()
                        .lambda().eq(ProduceProduct::getProduceId, pid)
                        .eq(ProduceProduct::getOrderProductId, producePrint.getOrderProductId()));
                if (products == null || products.isEmpty()) {
                    throw new ServiceException("印刷单没有找到对应的产品信息！");
                }
                ProduceProduct product = products.get(0);

                //查询印刷单下第一个贴分配的印
              List<ProducePiece> pieces=producePieceService.list(new QueryWrapper<ProducePiece>()
                        .lambda().eq(ProducePiece::getPrintId,producePrint.getPrintId()));
              if(pieces!=null&&pieces.size()>0) {
                  String pieceId = pieces.get(0).getPieceId();
                  List<MesProducePieceMachine> pieceMachines = mesProducePieceMachineService.list(new QueryWrapper<MesProducePieceMachine>()
                          .lambda().eq(MesProducePieceMachine::getPieceId, pieceId)
                          .eq(MesProducePieceMachine::getMachineType, '2'));
                  if (pieceMachines != null && pieceMachines.size() > 0) {
                      String machineId = pieceMachines.get(0).getMachineId();
                      MesMachine workshop = mesMachineService.getById(machineId);//分配的印刷车间

                      if (Objects.equals(product.getBindingMode(), "7") || Objects.equals(product.getBindingMode(), "9")) {
//                                return;//目录无需分配机台
                      } else {

                          //四色的分到二车间
                       if(product.getPrintColor().contains("7")||product.getPrintColor().contains("8")||product.getPrintColor().contains("9")
                       ||product.getPrintColor().contains("10")||product.getPrintColor().contains("11")){
//                       workshop.setWorkshopId("7");
                           seId="7";
                          }

                          if (Objects.equals(product.getBookSize(), "1")) {//如果开本数等于8
                              List<MesBindingAllocation> allocations = mesBindingAllocationService.list(new QueryWrapper<MesBindingAllocation>()
                                      .lambda().eq(MesBindingAllocation::getBookSize, product.getBookSize()));
//                              params.put(mesPrintTechnologyDetail.getMachineType(), allocations.get(0).getMachineId());
                              producePrint.setBindingMachine(allocations.get(0).getMachineId());
                              produceMapper.BindingFPMachine(producePrint);
                          } else {
                              List<MesBindingAllocation> bindingAllocations=new ArrayList<>();
                              String qd="5,10,6,8,11,15,14,17";
                              String[] listValues = qd.split(",");
                              List<String> qdlist= Arrays.asList(listValues);
                              if(qdlist.contains(product.getBindingMode())){//骑订
                                  if(Objects.equals(workshopId, "7")){
                                      bindingAllocations = mesBindingAllocationService.list(new QueryWrapper<MesBindingAllocation>()
                                              .lambda().eq(MesBindingAllocation::getPrintWorkshopId, workshopId)
                                              .like(MesBindingAllocation::getBindingMode, product.getBindingMode()));
                                  }else{
                                      bindingAllocations = mesBindingAllocationService.list(new QueryWrapper<MesBindingAllocation>()
                                              .lambda().eq(MesBindingAllocation::getPrintWorkshopId, workshop.getWorkshopId())
                                              .like(MesBindingAllocation::getBindingMode, product.getBindingMode()));
                                  }
                              }else {//胶订
                                  if (!seId.equals("0")) {
                                      bindingAllocations = mesBindingAllocationService.list(new QueryWrapper<MesBindingAllocation>()
                                              .lambda().eq(MesBindingAllocation::getPrintWorkshopId, seId)
                                              .like(MesBindingAllocation::getBindingMode, product.getBindingMode()));
                                  } else {
                                      if (!workshopId.equals("0")) {
                                          bindingAllocations = mesBindingAllocationService.list(new QueryWrapper<MesBindingAllocation>()
                                                  .lambda().eq(MesBindingAllocation::getPrintWorkshopId, workshopId)
                                                  .like(MesBindingAllocation::getBindingMode, product.getBindingMode()));
                                      } else {
                                          bindingAllocations = mesBindingAllocationService.list(new QueryWrapper<MesBindingAllocation>()
                                                  .lambda().eq(MesBindingAllocation::getPrintWorkshopId, workshop.getWorkshopId())
                                                  .like(MesBindingAllocation::getBindingMode, product.getBindingMode()));
                                      }
                                  }
                              }
//                               bindingAllocations = mesBindingAllocationService.list(new QueryWrapper<MesBindingAllocation>()
//                                      .lambda().eq(MesBindingAllocation::getPrintWorkshopId, workshop.getWorkshopId())
//                                      .like(MesBindingAllocation::getBindingMode, product.getBindingMode()));
                              if (bindingAllocations == null || bindingAllocations.size() == 0) {
                                  throw new ServiceException(workshop.getWorkshopName() + product.getBindingMode() + "装订方式" + "没有查到装订对应机台数据！");
                              } else {
                                  if (bindingAllocations.size() > 1) {//胶订
                                      String Machines ="";
                                      if(!seId.equals("0")){
                                          MesBindingAllocation binding1 = mesBindingAllocationService.list(new QueryWrapper<MesBindingAllocation>()
                                                  .lambda().eq(MesBindingAllocation::getPrintWorkshopId, seId)
                                                  .like(MesBindingAllocation::getBindingMode, product.getBindingMode())
                                                  .lt(MesBindingAllocation::getPrintSheet, product.getSheet())
                                                  .orderByDesc(MesBindingAllocation::getPrintSheet)).get(0);
                                          Machines = binding1.getMachineId();
                                      }else{
                                          if(!workshopId.equals("0")){
                                              MesBindingAllocation binding1 = mesBindingAllocationService.list(new QueryWrapper<MesBindingAllocation>()
                                                      .lambda().eq(MesBindingAllocation::getPrintWorkshopId, workshopId)
                                                      .like(MesBindingAllocation::getBindingMode, product.getBindingMode())
                                                      .lt(MesBindingAllocation::getPrintSheet, product.getSheet())
                                                      .orderByDesc(MesBindingAllocation::getPrintSheet)).get(0);
                                              Machines = binding1.getMachineId();
                                          }else{
                                              MesBindingAllocation binding1 = mesBindingAllocationService.list(new QueryWrapper<MesBindingAllocation>()
                                                      .lambda().eq(MesBindingAllocation::getPrintWorkshopId, "7")
                                                      .like(MesBindingAllocation::getBindingMode, product.getBindingMode())
                                                      .lt(MesBindingAllocation::getPrintSheet, product.getSheet())
                                                      .orderByDesc(MesBindingAllocation::getPrintSheet)).get(0);

                                              MesBindingAllocation binding2 = mesBindingAllocationService.list(new QueryWrapper<MesBindingAllocation>()
                                                      .lambda().eq(MesBindingAllocation::getPrintWorkshopId, "10")
                                                      .like(MesBindingAllocation::getBindingMode, product.getBindingMode())
                                                      .lt(MesBindingAllocation::getPrintSheet, product.getSheet())
                                                      .orderByDesc(MesBindingAllocation::getPrintSheet)).get(0);
                                              Machines = binding1.getMachineId()+","+binding2.getMachineId();
                                          }
                                      }

//                                      MesBindingAllocation binding1 = mesBindingAllocationService.list(new QueryWrapper<MesBindingAllocation>()
//                                              .lambda().eq(MesBindingAllocation::getPrintWorkshopId, "7")
//                                              .like(MesBindingAllocation::getBindingMode, product.getBindingMode())
//                                              .lt(MesBindingAllocation::getPrintSheet, product.getSheet())
//                                              .orderByDesc(MesBindingAllocation::getPrintSheet)).get(0);
//                                      MesBindingAllocation binding2 = mesBindingAllocationService.list(new QueryWrapper<MesBindingAllocation>()
//                                              .lambda().eq(MesBindingAllocation::getPrintWorkshopId, "10")
//                                              .like(MesBindingAllocation::getBindingMode, product.getBindingMode())
//                                              .lt(MesBindingAllocation::getPrintSheet, product.getSheet())
//                                              .orderByDesc(MesBindingAllocation::getPrintSheet)).get(0);

//                                      String Machines = bindingAllocation.getMachineId();//逗号隔开的机台组
//                                      String Machines = binding1.getMachineId()+","+binding2.getMachineId();//逗号隔开的机台组
                                      List<MesMachine> machines = produceMapper.getbindingLeast(Machines);//查询机台
                                      if (machines != null && machines.size() > 0) {
//                                          params.put(mesPrintTechnologyDetail.getMachineType(), machines.get(0).getPid());
                                          producePrint.setBindingMachine(machines.get(0).getPid());

                                          if(Objects.equals(workshopId, "0")){
                                           workshopId= getWorkshop(machines.get(0).getPid());
                                          }
                                          produceMapper.BindingFPMachine(producePrint);
                                      } else {
                                          throw new ServiceException("胶钉没有查到对应机台信息！");
                                      }
                                  } else {//骑马订
                                      String Machines = bindingAllocations.get(0).getMachineId();//逗号隔开的机台组
//                                      if (Objects.equals(producePrint.getPrintType(), "1")) {//印刷方式，1平张 2卷轮
                                          List<MesMachine> machines = produceMapper.getbindingLeast(Machines);//查询机台
                                          if (machines != null && machines.size() > 0) {
//                                              params.put(mesPrintTechnologyDetail.getMachineType(), machines.get(0).getPid());
                                              producePrint.setBindingMachine(machines.get(0).getPid());
                                              produceMapper.BindingFPMachine(producePrint);
                                          } else {
                                              throw new ServiceException("骑马钉没有查到对应机台信息！");
                                          }
//                                      }else{
//                                          producePrint.setBindingMachine(Machines.split(",")[0]);
//                                          produceMapper.BindingFPMachine(producePrint);
//                                      }
                                  }
                              }
                          }
                      }
                      }else{
                          throw new ServiceException(pieceId + "贴没有找到分配的印刷机台");
                      }
                  } else {
                      throw new ServiceException(producePrint.getPrintId() + "印刷没有找到对应的贴信息");
                  }
            }
        }
        return 1;
    }

}
